package com.kg.fiber.common;

import java.util.List;

import com.google.common.collect.Lists;

public class IntegerExpression {
	

	/**
	 * 解析离散整数表达式，
	 * <p>不同数据的位置采用‘,’号分隔，
	 * <p>连续数据可以用‘-’或者‘:’表示
	 * <p>如：‘0-4,6,8’
	 */
	public static List<Integer> parse(String expression) {
				
		if(expression == null) 
			return Lists.newArrayList();
		
		expression = expression.replaceAll("-", ":");
		
		List<Integer> lst = Lists.newLinkedList();
		
		try {
			
			String[] exps = expression.split(",");
			for(String exp : exps) {
				
				if(-1 != exp.indexOf(':')) {
					
					String[] p = exp.split(":");
					if(p.length == 2) {
						
						int i1 = Integer.parseInt(p[0]);
						int i2 = Integer.parseInt(p[1]);
						
						if(i1 <= i2 && i1 >= 0) {
							
							for(int i = i1; i <= i2; i++) {
								if(!lst.contains(i))
									lst.add(i);
							}
							
						}
						
					} else {
						
						throw new RuntimeException("表达式错误！");
						
					}
					
				} else {
					
					int i = Integer.parseInt(exp);
					
					if(i >= 0 && !lst.contains(i))
						lst.add(i);
					
				}
				
			}
			
		} catch(Exception e) {
			
			lst.clear();
			
		}
		
		return lst;
		

	}
	
	

}
